package query;

import java.util.StringTokenizer;
import java.util.Vector;

import document.InvertedIndex;
import document.Posting;
import document.StopWordLexicon;

public class ProximityTerm extends Term {

	Vector<String> subTerms;
	int proximityThreshold;

	public ProximityTerm(String name, int proximityThreshold) {
		super(name);
		this.proximityThreshold = proximityThreshold;

		subTerms = new Vector<String>();

		StringTokenizer token = new StringTokenizer(name,
				InvertedIndex.DELIMITERS);

		while (token.hasMoreTokens()) {
			String t = token.nextToken();

			if (!StopWordLexicon.getInstance().isStopWord(t)) {
				subTerms.add(t);
			}
		}
	}

	@Override
	public void process(InvertedIndex i) {

		// first make a normal AND search
		String queryString = "";
		for (String subTerm : subTerms) {
			queryString += subTerm + " and ";
		}
		queryString = queryString.substring(0, queryString.lastIndexOf(" and "));
		QueryBuilder qb = new QueryBuilder();
		qb.parse(queryString);
		Query q = qb.getQuery();
		q.process(i);
		
		//Now check proximity for returned results
		Vector<Integer> results = new Vector<Integer>();
		for (Integer docId : q.getResult()) {
			Vector<Posting> postings = new Vector<Posting>();
			for (String subTerm : subTerms) {
				postings.add(i.getPosting(docId, stemmer.stem(subTerm)));
			}

			boolean isWithinRange = true;
			if(postings.size() > 0)
			{
				Posting tempPosting = postings.get(0);
				for (int j = 0; j < postings.size() - 1; j++) {
					if (!tempPosting.isWithinWindow(postings.get(j + 1),
							proximityThreshold)) {
						isWithinRange = false;
					}
					else
					{
						tempPosting = tempPosting.getMatchedPostings();
					}
	
				}
				if (isWithinRange) {
					results.add(docId);
				} 
			}
		}

		queryResult = results;

	}

}
